import { WebSocketGateway, SubscribeMessage, MessageBody, ConnectedSocket } from '@nestjs/websockets';
import { WebsocketService } from './websocket.service';
import { CreateWebsocketDto } from './dto/create-websocket.dto';
import { UpdateWebsocketDto } from './dto/update-websocket.dto';
import { Observable } from 'rxjs';
import { Server } from 'socket.io';

@WebSocketGateway()
export class WebsocketGateway {
  constructor(private readonly websocketService: WebsocketService) {}

  @SubscribeMessage('createWebsocket')
  create(@MessageBody() createWebsocketDto: CreateWebsocketDto) {
    return this.websocketService.create(createWebsocketDto);
  }

  @SubscribeMessage('findAllWebsocket')
  findAll() {
    // return this.websocketService.findAll();
    // return {
    //   event: 'guang',
    //   data: this.websocketService.findAll()
    // }
    return new Observable((observer) => {
      observer.next({
        event: 'guang',
        data: {
          msg: 'aaa'
        }
      })
      setTimeout(() => {
        observer.next({
          event: 'guang',
          data: {
            msg: 'bbb'
          }
        })
      }, 2000);
      setTimeout(() => {
        observer.next({
          event: 'guang',
          data: {
            msg: 'ccc'
          }
        })
      }, 5000);
    })
  }

  @SubscribeMessage('findOneWebsocket')
  findOne(@MessageBody() id: number, @ConnectedSocket() server: Server) {
    server.emit('guang', 666)
    return this.websocketService.findOne(id);
  }

  @SubscribeMessage('updateWebsocket')
  update(@MessageBody() updateWebsocketDto: UpdateWebsocketDto) {
    return this.websocketService.update(updateWebsocketDto.id, updateWebsocketDto);
  }

  @SubscribeMessage('removeWebsocket')
  remove(@MessageBody() id: number) {
    return this.websocketService.remove(id);
  }
}
